/*
 *  Keybind Framework
 *  version 0.1
 *  Abe Yang <abeyang@cal.berkeley.edu> (c) 2006 
 *  
 *  Datagrid is freely distributable under the terms of an MIT-style license.
 *  Please visit <insert website> for more details.
/*--------------------------------------------------------------------------*/

// global hash
var keybindings = {};

var isIE = navigator.appVersion.match(/\bMSIE\b/);
var isSafari = /Konqueror|Safari|KHTML/.test(navigator.userAgent);
var isWindows = /Windows/.test(navigator.userAgent);

// [
//		{key: 'a', modifier: 'shift', fn: 'alert("a pressed!")', os: 'mac'},
//		{...}
// ]

// 'key' and 'fn' are required
// 'os' options: 'mac' or 'pc'
function keybind(bindings) {
	var mod;
	bindings.each(function(binding) {
		// fn
		if (binding.fn == null) {
			alert ('one of the functions (fn) is not defined!');
			return;
		}
		else fn = binding.fn;
		
		if (binding.os == 'mac') fn = 'if (!isWindows) {' + fn + '}';
		else if (binding.os == 'pc') fn = 'if (isWindows) {' + fn + '}';
		
		// key
		if (binding.key == null) {
			alert ('one of the keys is not defined!');
			return;
		}
		else key = binding.key.toUpperCase();
		
		if (key == 'ENTER') key = 'RETURN';
		
		// modifier
		mod = binding.modifier || '';
		keybindings[key + '_' + mod] = fn;
	});
	
	var hashkey;
	Event.observe(document, 'keyup', function(e){
		var mod = '';
		if (e.ctrlKey) mod = 'ctrl';
		else if (e.altKey) mod = 'alt';
		else if (e.shiftKey) mod = 'shift';
		else if (e.metaKey) mod = 'cmd';
		
		keycode = e.keyCode;
		if (keycode == Event.KEY_RETURN) keycode = 'RETURN';
		else keycode = String.fromCharCode(keycode);
		
		hashkey =  keycode + '_' + mod;
		//console.log(hashkey);
		var fn = keybindings[hashkey];
		if (fn)	eval(fn);
	});
}
